import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Spin, Button, Modal, Row, Col, Tooltip, Icon, } from 'antd';
import EditPage from '@/components/EditPage';
import DetailPage from '@/components/DetailPage';
import FileReader from '@/components/FileReader';
import AdButton from '@/components/AdButton';
import TableButtons from '@/components/TableButtons';
import FileImport from '@/components/FileImport';
import prompt from '@/components/Prompt';
import { formItemFragement, queryDict, queryPerson, formatPrice } from '@/utils/common';
import { allDictList } from '@/utils/constans';
import {
  selectDeclareDetailAndInfo,
  renderTableAdSelect,
  allDispatchType,
  codes,
  declareStatus,
  selectDeclareList
} from './utils';
import DeclareInfo from './DeclareInfo';
const { confirm } = Modal;
import styles from './declare.less';

@connect(({ declare, loading, component }) => ({
  declareDetail: declare.declareDetail,
  dictObject: component.dictObject,
  mdsDeliveryList:declare.mdsDeliveryList,
  loading: loading.effects[allDispatchType.detail],
}))
export default class DeclareDetail extends Component {
  state = {
    detailId: '',
    visibleFile: false,
    checkDeclare: '',
    checkContainer: '',
    totalWeith: 0,
    hasContainer: false
  };

  componentWillMount() {
    // 查询字典项
    const allDict = [allDictList.manifest_transport, allDictList.manifest_goods];
    queryDict({ props: this.props, allDict });
  }
  componentDidMount() {
    const { detailId, match, onRef } = this.props;
    const currentId = match && match.params.id ? match.params.id : detailId;
    if (!currentId) return;
    this.handleStateChange([{ detailId: currentId }]);
    this.getDeclareDetailAndInfo();
    this.containerByIdsList();
    this.getMdsDeliveryInfo();
    onRef && onRef(this)
  }

  getDeclareDetailAndInfo = () => {
    const { detailId, match } = this.props;
    const currentId = match && match.params.id ? match.params.id : detailId;
    currentId &&
      selectDeclareDetailAndInfo({
        type: allDispatchType.detail,
        payload: { id: currentId },
        props: this.props,
        callback: res => {
          if (res && res.manifestNo) {
            this.checkNum(res.manifestNo, 'checkDeclare');
          }
        },
      });
  };
  //集装箱：用于校验是否合格
  containerByIdsList = () => {
    const { dispatch, detailId, match } = this.props;
    const currentId = match && match.params.id ? match.params.id : detailId;
    currentId &&
      dispatch({
        type: allDispatchType.containerByIdsList,
        payload: { id: currentId },
        callback: data => {
          if (Array.isArray(data) && data.length > 0) {
            this.checkNum(data, 'checkContainer'); //集装箱货运号校验
            this.setState({
              hasContainer: true
            })
          } else {
            this.setState({
              hasContainer: false
            })
          }
        },
      });
  };
  //运单总货重：
  getMdsDeliveryInfo = () => {
    const { dispatch, detailId, match } = this.props;
    const currentId = match && match.params.id ? match.params.id : detailId;
    currentId &&
      dispatch({
        type: allDispatchType.getMdsDeliveryInfo,
        payload: { roadManifestId: currentId },
        callback: data => {
          this.setState({
            totalWeith: data ? data.TotalWeith : 0
          })
          console.log('data', data)
        },
      });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  //导入：
  handleImportFile = () => {
    const { visibleFile } = this.state;
    this.setState({ visibleFile: !visibleFile });
  };
  //提交   
  commitDeclare = flag => {
    const { dispatch, declareDetail ,mdsDeliveryList} = this.props;
    const { detailId, totalWeith, hasContainer } = this.state;
    const detail = declareDetail[detailId] || {};
    
    const _test=mdsDeliveryList[detailId]&&mdsDeliveryList[detailId].list?mdsDeliveryList[detailId].list:[]
    const hasRd01=_test.some(v=>v.goodsItemCode!='RD01')
    console.log('hasRd01==',hasRd01,mdsDeliveryList,)
    if (detail.status !== 'DRAFT') {
      prompt({ content: '只有状态是草稿的账单才能提交！', type: 'warn' });
      return;
    }
    if (!hasContainer && totalWeith && Number(totalWeith) > 8000) {
      prompt({ content: '货物总毛重不能超过8吨', type: 'error' });
      return;
    }
    
    let loadTime = new Date(detail.loadTime)
    let updateTime = new Date(detail.updateTime)
    let diffDay = loadTime - updateTime
    let days = Math.floor(diffDay / (24 * 3600 * 1000));
    if(loadTime < updateTime || days >= 5){
      prompt({ content: '装载时间必须在导入时间的5天内，请检查装载时间是否合规！', type: 'warn' });
      return;
    }
    const unit = {
      save: () => {
        dispatch({
          type: allDispatchType.save,
          payload: { id: detailId, flag },
          callback: data => {
            if (!data) return;
            selectDeclareDetailAndInfo({
              type: allDispatchType.detail,
              payload: { id: detailId },
              props: this.props,
              callback: data => {
                if (!data) return;
              },
            });
            selectDeclareList({ props: this.props, payload: formValues });
          },
        });
      },
    };

    if(_test.length>0&&hasRd01){
      // prompt({ content: '提运单中包含非RD01', type: 'error' });
      confirm({
        title: '提运单中包含非RD01!是否继续提交?',
        // icon: <ExclamationCircleOutlined />,
        content: '',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          unit.save();
        },
        onCancel() {
          return
        },
      });
      return
    }
    confirm({
      title: `提交后将不能再修改，确认提交？`,
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        unit.save();
      },
    });

   
  };

  checkNum = (data, type) => {
    let reg = '';
    let flag = true;
    if (type == 'checkDeclare') {
      //批次号：13位1100开头
      reg = /^(1100)/g;
      if (!reg.test(data) || data.length !== 13) {
        flag = false;
      }
    } else {
      //批次号：11位4位英文开头
      reg = /^[a-zA-Z]{4}/;
      if (Array.isArray(data) && data.length > 0) {
        data.map(v => {
          const str = v.containerNo;
          if (!reg.test(str) || str.length !== 11) {
            flag = false;
          }
        });
      }
    }
    this.setState({
      [type]: flag,
    });
  };

  headerOperate = detail => {
    return (
      <div>
        <AdButton
          onClick={() => this.commitDeclare(0)}
          disabled={detail.status == 'COMMIT' ? true : false}
          text="提交"
          type="primary"
          code={codes.commit}
        />
        {/* <AdButton
          onClick={() => this.handleImportFile()}
          text="导入"
          disabled={detail.status == 'COMMIT' ? true : false}
          style={{ marginLeft: 8 }}
        /> */}
      </div>
    );
  };

  render() {
    const { loading, declareDetail, pageType, match } = this.props;
    const { visibleFile, detailId, checkContainer, checkDeclare } = this.state;
    const detail = declareDetail[detailId] || {};

    const editPageParams = {
      title: detail.manifestOwnNo || '',
      headerOperate: !pageType ? this.headerOperate(detail) : '',
      panelTitle: ['舱单校验', '基础信息', '提运单明细'],
    };

    const formItem = [
      [
        <DetailPage label="单据号" value={detail.manifestOwnNo} />,
        <DetailPage
          label="状态"
          value={renderTableAdSelect({
            props: this.props,
            value: detail.status,
            data: declareStatus,
          })}
        />,
      ],
      [
        <DetailPage label="货物运输批次号" value={detail.manifestNo} />,
        <DetailPage
          label="运输方式"
          value={renderTableAdSelect({
            props: this.props,
            value: detail.transportMethodCode,
            key: allDictList.manifest_transport,
            declare: true,
          })}
        />,
      ],
      [
        <DetailPage
          label="进出境口岸海关"
          value={renderTableAdSelect({
            props: this.props,
            value: detail.customsCode,
            key: allDictList.manifest_goods,
            declare: true,
          })}
        />,
        <DetailPage label="承运人" value={detail.carrierBy} />,
      ],
      [
        <DetailPage label="货物装载时间" value={detail.loadTime} />,
        <DetailPage label="到达卸货地日期" value={detail.unloadTime} />,
      ],
      [
        <DetailPage label="卸货地代码" value={detail.unloadCode} />,
        <DetailPage label="企业代码" value={detail.enterpriceCode} />,
      ],
      [
        <DetailPage label="传输企业备案关区" value={detail.filingAreaName} />,
        <DetailPage label="舱单传输人名称" value={detail.transprotName} />,
      ],
      [<DetailPage label="运输工具代理企业代码" value={detail.enterpriceCode} />],
      [<DetailPage label="导入时间" value={detail.updateTime} />,
      <DetailPage label="备注" value={detail.remarks} />],
    ];

    return (
      <Fragment>
        {/* <FileImport
          visibleFile={visibleFile}
          handleCancel={() => {
            this.handleImportFile();
          }}
          urlImport={`mds/mds-road-manifest/importUpdateMdsRoadManifest?id=${detailId}`} 
          queryData={[this.getDeclareDetailAndInfo]}
          urlCase={`attachment/舱单导入模板.xls`}
          accept=".xls,.xlsx"
        /> */}
        <EditPage {...editPageParams}>
          <Row className={styles.declare_check} gutter={16}>
            <Col span={12}>
              <label className="text">货物运输批次号：</label>
              {checkDeclare ? (
                <b className="value green">合规</b>
              ) : checkDeclare === false ? (
                <Tooltip title="货物运批次号应以“1100”开头的14位数">
                  <b className="value red">
                    不合规
                    <Icon
                      type="exclamation-circle"
                      style={{ fontSize: 15, marginLeft: 2, color: '#fff' }}
                    />
                  </b>
                </Tooltip>
              ) : (
                    <b>无</b>
                  )}
            </Col>
            <Col span={12}>
              <label className="text">集装箱号：</label>
              {checkContainer ? (
                <b className="value green">合规</b>
              ) : checkContainer === false ? (
                <Tooltip title="集装箱号以4位英文开头的11位数">
                  <b className="value red">
                    不合规
                    <Icon
                      type="exclamation-circle"
                      style={{ fontSize: 15, marginLeft: 2, color: '#fff' }}
                    />
                  </b>
                </Tooltip>
              ) : (
                    <b>无</b>
                  )}
            </Col>
          </Row>
          <Spin spinning={loading}>{formItemFragement(formItem)}</Spin>
          <Fragment>
            <DeclareInfo
              detailId={detailId}
              mode="detail"
              isMobile={this.props.isMobile}
              pageType={pageType}
            />
          </Fragment>
        </EditPage>
      </Fragment>
    );
  }
}
